package cn.tedu.weibo.controller;

import cn.tedu.weibo.entity.User;
import cn.tedu.weibo.entity.Weibo;
import cn.tedu.weibo.mapper.WeiboMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/weibo/insert")
    public int insert(Weibo weibo, MultipartFile picFile , HttpSession session) throws IOException {
        User u = (User) session.getAttribute("u");
        if (u==null){
            return 0;
        }
        //得到原始文件名
        String fileName = picFile.getOriginalFilename();
        //得到后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名
        fileName = UUID.randomUUID()+suffix;
        //准备文件夹
        String dirPath = "D:/upload";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath+"/"+fileName;
        //保存文件
        picFile.transferTo(new File(filePath));
        //
        weibo.setUrl("/"+fileName);
        //把当前登录的用户信息保存在weibo对象中
        weibo.setAuthor(u.getNick());
        weibo.setUserId(u.getId());
        //得到系统时间
        weibo.setCreated(new Date());
        System.out.println("weibo="+weibo);
        mapper.insert(weibo);
        return 1;//表示下载成功
    }
    @RequestMapping("/weibo/select")
    public List<Weibo> select(){

        return mapper.select();
    }
    @RequestMapping("/weibo/selectById")
    public Weibo selectById(int id){
        return mapper.selectById(id);
    }

}
